#coding: utf8
'''
==================================================================================
Created on 2020-10-26
Author: Simon
==================================================================================
'''

from datetime import datetime
from src.libs.database import Database
from src.common.base import Task, WorkRecord, id_null, workday as WD
import src.task as T



def list_submit_status(department=None, user=None, workday=None, db=None):
    db = Database()
    if not workday: workday = WD()
    sql = "select user, count(*) ct from record_day where workday=%s"
    params = [workday]
    if department:
        sql += " and user in (select username from user where orgId=%s)"
        params.append(department)
    if user: 
        sql += " and user=%s"
        params.append(user)
    sql += " group by user"
    res = db.read_all(sql, params)
    
    return res

def get_submit_status(user=None, workday=None):
    res = list_submit_status(None, user, workday)
    return len(res) != 0


def list_record_today(user, db=None):
    sql = "select id from record_day where user=%s and workday=%s"
    params = [user, WD()]
    ids = db.read_all(sql, params)
    return [d['id'] for d in ids]
    

def submit_record(user, jobs, plans):
    db = Database()
    '''检查今天是否已提交过日报'''
    ids = list_record_today(user, db)
    ts = list(set(d['tid'] for d in jobs if not id_null(d['tid'])))
    ctls = T.get_task_ctls(user, ts, db)
    
    comands = []
    jps, keys, texts = [{}, {}], ["job", "plan"], ["任务", "计划"]
    for i, rs in enumerate([jobs, plans]):  
        for r in rs: 
            w = WorkRecord()
            w.load_data(user, r)
            sql, params = w.get_sql(i)
            comands.append([sql, params])
            
            if w.task_id == None:
                if w.task == "": return False, "任务不能为空！" 
                continue 
            if int(w.task_id) == -1: continue
            if w.task_id in jps[i]: return False, "%s项重复！" % texts[i]
            jps[i][w.task_id] = w.progress 
            
            info = ctls.get(w.task_id, None)
            flag, msg = check_record(w, jps[0], info, keys[i])
            if not flag: return flag, msg 
        '''End For 2'''
    '''End For 1'''
    
    '''转储先前提交的记录'''
    comands = deal_pre_records(user, ids) + comands
    
    flag, data = db.Transaction(comands)
    if not flag: data = "请检查数据或其它错误，当前配置仅支持从任务库选取任务！"
    
    return flag, data

'''转储先前提交的记录·计划直接删除，不做备份'''
def deal_pre_records(user, ids):
    commands = []
    if ids: 
        whr = " where id in ({})".format(','.join('%s' for d in ids))
        commands += [
            ["delete from record_day_del where user=%s and workday=%s", [user, WD()]], 
            ["insert into record_day_del select * from record_day " + whr, ids],
            ["delete from record_day " + whr, ids],
            ["delete from plan_day where user=%s and workday=%s", [user, WD()]],
        ]
    '''End If'''
    return commands


def check_record(record, jps, info, key="plan"):
    word = {'plan': "计划", 'job': "完成"}[key]
    tid, p = record.task_id, record.progress
    '''计划进度不能小于本日进度'''
    if key=="plan" and p < jps.get(tid, 0): 
        return False, "任务的计划进度不能小于本日完成进度！"
    if not info: return True, "核验通过" 
    
    if p < info['min']: 
        return False, "%s进度不能小于当前进度，请核对或先进行任务计划变更！" % word
        
    if key=="job" and info['progress'] != None and p != info['progress']: 
        return False, "该任务进度本日已有协作成员提交，请核对或先进行任务计划变更！"
    
    return True, "核验通过"

def create_record(user, category, task_id, module_id, project_id, workday, \
                  progress, content="", mark="", leader=""):
    d = WorkRecord(category, project_id, module_id, task_id, None)
    d.set_data(user, workday, progress, content, mark, leader)
    d.create()
    

''' 保存个人每日日志的总结部分 '''
def save_report_sum(user, workday, record, summary):
    db = Database()
    sql = "replace into record_sum(user, workday, record, summary) VALUES (%s, %s, %s, %s)"
    params = [user, workday, record, summary]
    flag = db.execute(sql, params)
    if flag == -1: return False, "保存失败"

    return True, flag

''' 获取部门日报 '''
def get_report_org(begin_time, end_time, department):
    db = Database()
    sql = '''select r.user user, realName name, postLabel, workday, summary from record_sum r 
        left join user u on r.user=u.username where r.workday>=%s and r.workday<=%s 
        and u.orgId=%s order by u.dayOrder'''
    res = db.read_all(sql, [begin_time, end_time, department])
    cache = {}
    content = ""
    for item in res:
        name, label, workday, summary = item['name'], item['postLabel'], item['workday'], item['summary']
        key = name + "_" + str(workday) 
        if key not in cache: 
            cache[key] = item
            content += "【%s·%s】\n" % (label, name)
        content += summary + "\n"
    
    return content 

''' 
    获取项目时间占用汇总 
    * 因后续前端可能增加可视化展示，故本查询返回结构化数据，不做结果字符串拼接
    TODO：暂不考虑sql性能
        项目模块参与天数汇总并不准确，需单独二次查询
'''    
def get_proj_time_sum(begin_time, end_time, user, department=None):
    db = Database()
    params = [begin_time, end_time]
    whr1, whr2, fs = "workday between %s and %s ", "", ""
    if department == None:
        whr1 += " and user=%s"
        params += [user, begin_time, end_time, user]
    else:
        fs = " realName, "
        whr2 = "left join user u on user=u.username where u.orgId=%s"
        params += [begin_time, end_time, department]
    '''End If'''
    # select * from record_day where workday between '2022-07-02' and '2022-07-11' and user='zhaozhikai'
    
    sql = '''
    select user, {} project, module, count(workday) cw, sum(mct/ct) st from (SELECT user u, workday w, count(1) ct 
    from record_day where {} group by user, workday) a right join (
        SELECT user, workday, project, module, count(1) mct from record_day where {} 
        group by user, workday, project, module
    ) b on a.u=b.user and a.w=b.workday {} group by user, project, module 
    '''.format(fs, whr1, whr1, whr2)
    items = db.read_all(sql, params)
    
    ps, countDay = {}, 0
    for item in items:
        item['cw'], item['st'] = float(item['cw']), float(item['st'])
        u, p, m, day, tm = item['user'], item['project'], item['module'], item['cw'], item['st']
        if department == None: continue
        name = item['realName']
        if p not in ps: ps[p] = {'person': {}, 'module': {}, 'day': 0, 'time': 0}
        if name not in ps[p]['person']: ps[p]['person'][name] = 1
        if m not in ps[p]['module']: ps[p]['module'][m] = {'day': 0, 'time': 0, 'person': {}}
        if u not in ps[p]['module'][m]['person']: ps[p]['module'][m]['person'][u] = 1
        ps[p]['day'] += day
        ps[p]['time'] += tm
        ps[p]['module'][m]['day'] += day
        ps[p]['module'][m]['time'] += tm
        countDay += tm
    
    return {"detail": items, 'times': countDay, 'summary': ps}

        

    
if __name__ == '__main__':
    # create_record("admin", 0, None, None, None, "2020-10-26", 98, "写文档", "无", "刘备")
    # get_submit_status("admin2")
    get_proj_time_sum(None, None, 'zhaozhikai', None)
    
    pass